package com.xnew.manager.elevator.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.log.mapper.OperLogRecordMapper;
import com.xnew.manager.elevator.entity.ElevatorInfo;
import com.xnew.manager.elevator.entity.MaintPers;
import com.xnew.manager.elevator.mapper.ElevatorMapper;
import com.xnew.manager.elevator.mapper.MaintPersMapper;
import com.xnew.manager.elevator.service.ElevatorService;
import com.xnew.utils.DataInput;
import com.xnew.utils.DataOutput;
import com.xnew.utils.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ElevatorServiceImpl implements ElevatorService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 电梯基本信息mapper
     */
    @Resource
    private ElevatorMapper elevatorMapper;

    /**
     * 电梯维保人信息mapper
     */
    @Resource
    private MaintPersMapper maintPersMapper;

    /**
     * 电梯操作日表记录表
     */
    @Resource
    private OperLogRecordMapper operLogRecordMapper;

    /**
     * 电梯列表
     *
     * @param input
     * @return
     */
    @Override
    public List<ElevatorInfo> elevatorList(DataInput input) {
        if (input.getPageNum() != null && input.getPageSize() != null) {
            PageHelper.startPage(input.getPageNum(), input.getPageSize());
        }
        return elevatorMapper.elevatorList(input.getParam());
    }

    /**
     * 电梯新增
     *
     * @param elevatorInfo
     * @param userInfo
     * @return
     */
    @Override
    public DataOutput elevatorAdd(ElevatorInfo elevatorInfo, SysUserInfo userInfo) {
        DataOutput out = DataOutput.success();
        try {
            elevatorInfo.setElId(IdUtils.getIncreaseIdByNanoTime());//id
            elevatorInfo.setCreateDate(DateUtil.now());//创建时间
            elevatorInfo.setCreateUser(userInfo.getUserInfoNo());//创建人
            elevatorInfo.setOrgId(userInfo.getOrgUserNo());//机构id
            elevatorInfo.setIsState("");//电梯信息状态
            elevatorMapper.insert(elevatorInfo);
            //电梯维保负责人表
            List<MaintPers> maintPersList = new ObjectMapper().convertValue(elevatorInfo.getMaintPersList(), new TypeReference<List<MaintPers>>() {
            });
            for (MaintPers maintPers : maintPersList) {
                maintPers.setMaintPersId(IdUtils.getIncreaseIdByNanoTime());//维保人信息id
                maintPers.setElId(elevatorInfo.getElId());//电梯信息id
                maintPers.setIsState("");//维保人状态
            }
            maintPersMapper.saveBatch(maintPersList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.setCode(500);
            out.setMsg("操作失败！");
            return out;
        }
        return out;
    }

    /**
     * 电梯修改
     *
     * @param elevatorInfo
     * @param userInfo
     * @return
     */
    @Override
    public DataOutput elevatorUpdate(ElevatorInfo elevatorInfo, SysUserInfo userInfo) {
        DataOutput out = DataOutput.success();
        try {
            //电梯基本信息
            elevatorInfo.setUpdateUser(userInfo.getUserInfoNo());//修改人
            elevatorInfo.setUpdateDate(DateUtil.now());//修改时间
            elevatorMapper.updateById(elevatorInfo);
            //电梯维保负责人表
            HashMap<String, Object> maintPersMap = new HashMap<>();
            maintPersMap.put("el_id", elevatorInfo.getElId());
            maintPersMapper.deleteByMap(maintPersMap);
            List<MaintPers> maintPersList = new ObjectMapper().convertValue(elevatorInfo.getMaintPersList(), new TypeReference<List<MaintPers>>() {
            });
            for (MaintPers maintPers : maintPersList) {
                maintPers.setMaintPersId(IdUtils.getIncreaseIdByNanoTime());//维保人信息id
                maintPers.setElId(elevatorInfo.getElId());//电梯信息id
                maintPers.setIsState("");//维保人状态
            }
            maintPersMapper.saveBatch(maintPersList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.setCode(500);
            out.setMsg("操作失败！");
            return out;
        }
        return out;
    }

    /**
     * 根据id查询电梯基本信息
     *
     * @param elId
     * @return
     */
    @Override
    public ElevatorInfo elevatorDetailById(String elId) {
        ElevatorInfo elevatorInfo = elevatorMapper.selectById(elId);
        Map maintPersMap = new HashMap<String, Object>();
        maintPersMap.put("el_id", elId);
        elevatorInfo.setMaintPersList(maintPersMapper.selectByMap(maintPersMap));
        //债券操作日志记录表
//        Map<String, Object> logData = new HashMap<>();
//        logData.put("busiTypeCode", Constant.BOND_BUSI_SUBMTD);
//        logData.put("vrsBusiTypeTabPk", elId);
//        List<OperLogRecord> operLogRecordList = operLogRecordMapper.selectByBusiId(logData);
//        if (operLogRecordList != null && operLogRecordList.size() > 0) {
//
//        }
        return elevatorInfo;
    }

    /**
     * 电梯生效/失效
     *
     * @param elevatorInfo
     * @param userInfo
     * @return
     */
    @Override
    public DataOutput elevatorEffectiveOrInvalid(ElevatorInfo elevatorInfo, SysUserInfo userInfo) {
//        OperLogRecord operLogRecord = new OperLogRecord();
//        operLogRecord.setLogRecordId(IdUtils.getIncreaseIdByNanoTime());//id
//        operLogRecord.setVrsBusiTypeTabPk(elevatorInfo.getElId());//业务id
//        operLogRecord.setFlowStepName("提交");//流程名
//        operLogRecord.setAuditStatusCode(Constant.BLACKLIST_INFORMATION_STATUS_CODE_0);
//        operLogRecord.setOperResultDesc("");//审核意见描述
//        operLogRecord.setOperPsnNo(userInfo.getUserInfoNo());//操作人
//        operLogRecord.setOperTime(DateUtil.now());//操作时间
//        operLogRecordMapper.insert(operLogRecord);
        DataOutput out = DataOutput.success();
        try {
            elevatorMapper.updateById(elevatorInfo);
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.setCode(500);
            out.setMsg("操作失败！");
            return out;
        }
        return out;
    }

    /**
     * 删除电梯信息
     *
     * @param elId
     * @return
     */
    @Override
    public DataOutput elevatorDelete(String elId) {
        DataOutput out = DataOutput.success();
        ElevatorInfo elevatorInfo = new ElevatorInfo();
        try {
            elevatorInfo.setElId(elId);
            elevatorInfo.setIsState("-1");
            elevatorMapper.updateById(elevatorInfo);
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.setCode(500);
            out.setMsg("操作失败！");
            return out;
        }
        return out;
    }

    @Override
    public DataOutput elevatorImportSave(MultipartFile multipartFile, SysUserInfo userInfo) {
        DataOutput out = DataOutput.success();
        InputStream inputStream = null;
        ElevatorInfo elevatorInfo = new ElevatorInfo();
        try {
            inputStream = multipartFile.getInputStream();
            //获取sheet1
            ExcelReader reader1 = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
            List<List<Object>> read1 = reader1.read(1, reader1.getRowCount()); // 读取第二行到最后一行数据
            List<ElevatorInfo> debts = new ArrayList<>();// 主表信息list
            //循环sheet1的第一行
            for (List<Object> object1 : read1) {
                if (object1.size() == 16) {
                    out.setCode(-90020);
                    out.setMsg("数据解析失败！");
                    return out;
                }
                Object elType = object1.get(0);//电梯类型
                //解析的数据
                elevatorInfo.setElType(elType.toString());//电梯类型
                debts.add(elevatorInfo);
            }
            //电梯基本信息
//            elevatorMapper.saveBatch(debts);
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.setCode(500);
            out.setMsg("操作失败！");
            return out;
        }
        return out;
    }
}
